import React ,{forwardRef,useState,useEffect}from 'react'
import {Form, Input,Select} from 'antd'
const { Option } = Select;

const UserForm = forwardRef((props,ref) =>{
  const [isDisabled, setisDisabled] = useState(false)
  useEffect(() => {
    setisDisabled(props.isUpdateDisabled)
  }, [props.isUpdateDisabled])
  const {roleId,region} = JSON.parse(localStorage.getItem('token'))
  const roleObj = {
    '1':'superAdmin',
    '2':'admin',
    '3':'editor'
  }
  const checkReginDisabled = (item)=>{
    if(props.isUpate){
      if(roleObj[roleId] === 'superAdmin'){
        return false
      }else{
        return true
      }
    } else{
      if(roleObj[roleId] === 'superAdmin'){
        return false
      }else{
        return item.value!==region
      }
    }
  }
  const checkRoleDisabled = (item)=>{
    if(props.isUpate){
      if(roleObj[roleId] === 'superAdmin'){
        return false
      }else{
        return true
      }
    } else{
      if(roleObj[roleId] === 'superAdmin'){
        return false
      }else{
        return roleObj[item.id] !== 'editor'
      }
    }
  }
  return (
    <div>
        <Form layout="vertical" ref={ref}>
        <Form.Item
          name="username"
          label="用户名"
          rules={[{ required: true, message: '必填!!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[{ required: true, message: '必填!!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="region"
          label="区域"
          rules={isDisabled?[]:[{ required: true, message: '必填!!' }]}
        >
          <Select disabled={isDisabled}>
            {
              props.regionList.map(item=>
                <Option value={item.value} key={item.id} disabled={checkReginDisabled(item)}>{item.title}</Option> 
              )
            }
          </Select>
        </Form.Item>
        <Form.Item
          name="roleId"
          label="角色"
          rules={[{ required: true, message: '必填!!' }]}
        >
          <Select onChange={(value)=>{
            if(value===1){
              setisDisabled(true)
              ref.current.setFieldsValue({
                region:''
              })
            }else{
              setisDisabled(false)
            }
          }}>
            {
              props.roleList.map(item=>
                <Option value={item.id} key={item.id} disabled={checkRoleDisabled(item)}>{item.roleName}</Option> 
              )
            }
          </Select>
        </Form.Item>
      </Form>
    </div>
  )
})
export default UserForm
